package com.mzpai.product.service.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gexin.fastjson.JSONArray;
import com.gexin.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mzpai.product.constant.ProductConstants;
import com.mzpai.product.mapper.StoreProductMapper;
import com.mzpai.product.model.StoreBrand;
import com.mzpai.product.model.StoreProduct;
import com.mzpai.product.model.StoreProductAttr;
import com.mzpai.product.model.StoreProductAttrResult;
import com.mzpai.product.model.StoreProductAttrValue;
import com.mzpai.product.model.StoreProductAttrValueSupplier;
import com.mzpai.product.model.StoreProductCate;
import com.mzpai.product.model.StoreProductDetails;
import com.mzpai.product.service.StoreBrandService;
import com.mzpai.product.service.StoreProductAttrResultService;
import com.mzpai.product.service.StoreProductAttrService;
import com.mzpai.product.service.StoreProductAttrValueService;
import com.mzpai.product.service.StoreProductAttrValueSupplierService;
import com.mzpai.product.service.StoreProductCateService;
import com.mzpai.product.service.StoreProductDetailsService;
import com.mzpai.product.service.StoreProductService;
import com.mzpai.product.service.StoreProductSupplierService;
import com.mzpai.product.vo.StoreProductDto;
import com.mzpai.product.vo.StoreProductSkuDto;
import com.mzpai.product.vo.UpdateStoreProductWaitPutReqVo;
import com.mzpai.service.impl.BaseServiceImpl;
import com.mzpai.util.BeanUtils;
import com.mzpai.util.DateUtil;
import com.mzpai.util.PageUtil;
import com.mzpai.util.StringUtils;
/**
 *
 * <b>使用帮助 | Service</b><br>
 *
 * yanglijun 2021-03-15 18:00:20
 * 
 *  @version 1.0.0
 *
 */
@Service
public class StoreProductServiceImpl extends BaseServiceImpl<StoreProduct> implements StoreProductService {

	Logger logger = LoggerFactory.getLogger(StoreProductServiceImpl.class);

	@Autowired 
	private StoreProductMapper storeProductMappermapper;
	@Autowired 
	private StoreProductCateService storeproductCateService;
	@Autowired 
	private StoreProductAttrResultService storeProductAttrResultService;
	@Autowired 
	private StoreProductAttrService storeProductAttrService;
	
	@Autowired 
	private StoreProductDetailsService productDetailsService;
	@Autowired 
	private StoreProductSupplierService storeProductSupplierService;
	@Autowired 
	private StoreProductAttrValueService storeProductAttrValueService;
	@Autowired 
	private StoreBrandService storeBrandService;
	
	@Autowired
	private StoreProductAttrValueSupplierService storeProductAttrValueSupplierService;
	
	

	@Override
	public StoreProduct queryByPrimaryId(Integer id) {
		StoreProduct storeProduct=storeProductMappermapper.queryByPrimaryId(id);
		return storeProduct;
	}

	@Override
	public List<StoreProduct> queryByProductCodeAndStoreId(String productCode,Integer storeId) {
		List<StoreProduct> storeProduct=storeProductMappermapper.queryByProductCodeAndStoreId(productCode,storeId);
		return storeProduct;
	}

	
	/***
	 * 更新操作
	 */
	@Override
	public void updateInfo(UpdateStoreProductWaitPutReqVo vo) {
		Integer productId = vo.getId();
		
		//商品服务类型 1:实物类; 2:服务类
		String productType=vo.getProductType();
				
		StoreProduct product = new StoreProduct();
		//设置更新值
		BeanUtils.copy(vo, product);
		addSliderImage(product);
		product.setIsShow(1);
		//设置价格，是规格的最底价格，到商品基本信息上
		addProducetLowPrice(product, vo.getStoreProductAttrValueList());
		//商品规格图片
		/**
		 * 详情设置
		 * 1.设置商品主体信息(eb_store_product)
		 * 2.设置更新 商品分类辅助表(eb_store_product_cate)
		 * 3.设置 商品属性表(eb_store_product_attr)
		 * 4.设置 商品属性值表(eb_store_product_attr_value)
		 * 5.设置商品详情表(eb_store_product_details)
		 * 6.商品属性详情表(eb_store_product_attr_result)
		 * 
		 */
		
		 if(productType!=null && productType.equals(ProductConstants.PRODUCT_TYPE_2)){
	        product.setStock(99);
		 }
		
		 //1.更新商品主体信息(eb_store_product)
		 storeProductMappermapper.update(product);
		 
		 //2.更新 商品分类辅助表(eb_store_product_cate)
		 addProductCate(product);
		 
		 /**3. 增加门店商品规格*/
		List<StoreProductAttr> attrList = vo.getStoreProductAttrList();
		addProductAttr(attrList, productId);	
		/**4. 设置 商品属性值表*/
		List<StoreProductAttrValue> attrValueList = vo.getStoreProductAttrValueList();
		addProductAttrValue(attrValueList, productId, product.getStoreId(),productType);
		
		
		/**5. 增加门店商品明细*/
		List<StoreProductDetails> detailsList = vo.getStoreProductDetailsList();
		addStoreProductDetails(detailsList, productId, product.getProductCode());
		
		/**6. 增加门店商品规格明细*/
		addProductAttrResult(attrValueList, productId, attrList);
		
	}

	
	

	/***
	 * 处理图片格式
	 * @param product
	 */
	private void addSliderImage(StoreProduct product) {
		if(StringUtils.isNoneBlank(product.getSliderImage())) {
			product.setSliderImage(product.getSliderImage());
		}
	}

	/***
	 * 保存商品信息
	 * 1.设置商品主体信息(eb_store_product)
	 * 2.设置更新 商品分类辅助表(eb_store_product_cate)
	 * 3.设置 商品属性表(eb_store_product_attr)
	 * 4.设置 商品属性值表(eb_store_product_attr_value)
	 * 5.设置商品详情表(eb_store_product_details)
	 * 6.商品属性详情表(eb_store_product_attr_result)
	 * 
	 * 7. 门店商品同步到商品库   规格， 明细, 属性值 详情
	 */
	@Override
	public int saveInfo(UpdateStoreProductWaitPutReqVo vo) {
		
		//商品服务类型 1:实物类; 2:服务类
		String productType=vo.getProductType();
		int productId = 0;
		/**1. 保存商品基本信息*/
		StoreProduct product = new StoreProduct();
		BeanUtils.copy(vo, product);
		addSliderImage(product);
		addProducetDefault(product);
		
		//设置价格，是规格的最底价格，到商品基本信息上
		addProducetLowPrice(product, vo.getStoreProductAttrValueList());
		
        if(productType.equals(ProductConstants.PRODUCT_TYPE_2)){
        	product.setStock(99);
		}
		super.save(product);
		productId = product.getId();
		
		/**2.设置更新 商品分类辅助表*/
		addProductCate(product);
		
		/**3. 增加门店商品规格*/
		List<StoreProductAttr> attrList = vo.getStoreProductAttrList();
		addProductAttr(attrList, productId);	
		/**4. 设置 商品属性值表*/
		List<StoreProductAttrValue> attrValueList = vo.getStoreProductAttrValueList();
		addProductAttrValue(attrValueList, productId, product.getStoreId(),productType);
		
		
		/**5. 增加门店商品明细*/
		List<StoreProductDetails> detailsList = vo.getStoreProductDetailsList();
		addStoreProductDetails(detailsList, productId, product.getProductCode());
		
		/**6. 增加门店商品规格明细*/
		addProductAttrResult(attrValueList, productId, attrList);
		
		
		/**
		 * 只有实物商品并且条形码不存在情况下才同步商品库
		 */
		boolean isSynchronizeFlag=true;
		
		if(productType.equals(ProductConstants.PRODUCT_TYPE_1)){
			for(StoreProductAttrValue attrValueVo:attrValueList){
				String attrValueBarCode=attrValueVo.getBarCode();
				Map<String,Object> attrValueMap=new HashMap<String,Object>();
				attrValueMap.put("barCode", attrValueBarCode);
				List<StoreProductAttrValueSupplier> queryAttrValueList=storeProductAttrValueSupplierService.getList(attrValueMap);
				if(queryAttrValueList!=null && !queryAttrValueList.isEmpty()){
					isSynchronizeFlag=false;
					break;
				}
			}
		}
		
		if(isSynchronizeFlag && productType.equals(ProductConstants.PRODUCT_TYPE_1)){
			/**7. 门店商品同步到商品库   规格， 明细, 属性值 详情*/
			storeProductSupplierService.addProductInfo(product);
		}
		return productId;
	}
	
	/**
	 * 设置价格，是规格的最底价格，到商品基本信息上
	 * @param product
	 */
	private void addProducetLowPrice(StoreProduct product, List<StoreProductAttrValue> attrValueList) {
		if(attrValueList != null && attrValueList.size() > 0) {
			int mp = 900000000;
			for(StoreProductAttrValue s : attrValueList) {
				if(s.getPrice().intValue() < mp && s.getState()==1) {
					product.setPrice(s.getPrice());
					product.setCost(s.getCost() == null ? new BigDecimal(0) : s.getCost());
					product.setMinPrice(s.getMinPrice() == null ? new BigDecimal(0) : s.getMinPrice());
					product.setOtPrice(s.getMinPrice() == null ? new BigDecimal(0) : s.getMinPrice());
					product.setStock(s.getStock());
					mp = s.getPrice().intValue();
				}
			}
		}
	}

	private void addProducetDefault(StoreProduct product) {
		product.setBrandId(getStoreAddBrandId("默认"));
		product.setMerId(product.getStoreId());
		product.setProductCode(StringUtils.getBusinessCode("SP"));
		product.setBarCode("");
		product.setTags("正品保证");
		product.setVipPrice(BigDecimal.valueOf(0D));
		product.setSort(Short.valueOf("0"));
		product.setPostage(BigDecimal.valueOf(0D));
		product.setSales(0);
		product.setStock(0);
		product.setIsShow(1);
		product.setIsHot(0);
		product.setIsBenefit(0);
		product.setIsBest(0);
		product.setIsNew(0);
		product.setMinPrice(BigDecimal.valueOf(0D));
		product.setIsPostage(0);
		product.setIsDel(0);
		product.setMerUse(0);
		product.setGiveIntegral(BigDecimal.valueOf(0D));
		product.setIsGood(0);
		product.setIsSeckill(0);
		product.setIsBargain(0);
		product.setAddTime(DateUtil.getUTCTime(null).intValue());
		product.setIsSub(0);
		product.setVideoLink("");
		product.setCodePath("");
		product.setUnitName(StringUtils.isNoneBlank(product.getUnitName()) ? product.getUnitName() : "个");
		product.setFactoryPid(0);
		product.setFactoryProductId(0);
		product.setFactoryId(0);
		product.setActivity("");
		product.setFicti(0);
		product.setBrowse(0);
		product.setIsCopy(0);
		product.setTempId(0);
		product.setCost(BigDecimal.valueOf(0D));
		product.setOtPrice(BigDecimal.valueOf(0D));
		product.setPrice(BigDecimal.valueOf(0D));
		product.setStoreInfo(StringUtils.isEmpty(product.getStoreInfo()) ? "" : product.getStoreInfo());
	}

	/**
	 * 获取品牌， 有就返回id， 没有就新增，返回ID
	 * @param brandName
	 * @return
	 */
	private Integer getStoreAddBrandId(String brandName) {
		Integer brandId = 0;
		if(StringUtils.isNoneBlank(brandName)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("brandName", brandName);
			List<StoreBrand> list = storeBrandService.getList(map);
			if(!list.isEmpty()) {
				brandId = list.get(0).getBrandId();
			} else {
				StoreBrand v = new StoreBrand();
				v.setBrandName(brandName);
				v.setBrandCode(StringUtils.getRandomCode(6));
				storeBrandService.save(v);
				brandId = v.getBrandId();
			}
		}
		return brandId;
	}

	/***
	 * 6.设置 商品属性值表
	 * @param product
	 */
	private void addProductAttrResult(List<StoreProductAttrValue> attrValueList, Integer productId, List<StoreProductAttr> attrList) {
		
		String result = getProductAttrResultString(attrValueList, attrList);
		storeProductAttrResultService.deleteByProductIdAndType(productId, ProductConstants.ACTIVE_TYPE_0);
		StoreProductAttrResult target = new StoreProductAttrResult();
		target.setProductId(productId);;
		target.setResult(result);
		target.setType(0);
		target.setChangeTime(DateUtil.getUTCTime(null).intValue());
		storeProductAttrResultService.save(target);
	}

	/**
	 * 特殊拼接方法
	 * @param attrValueList
	 * @param attrList
	 * @return
	 */
	private String getProductAttrResultString(List<StoreProductAttrValue> attrValueList, List<StoreProductAttr> attrList) {
		/**
		 *  拼接：
		 *  [
		 *  	{"attrHidden":false,"detailValue":"","detail":["白色","黑色"],"value":"颜色"},
		 *  	{"attrHidden":false,"detailValue":"","detail":["10G","20G","30G"],"value":"重量"}
		 *  ]
		 */
		JSONArray arr = new JSONArray(); 
		for(StoreProductAttr s : attrList) {
			JSONObject o = new JSONObject();
			o.put("value", s.getAttrName());
			o.put("detailValue", "");
			o.put("attrHidden", false);
			o.put("detail", s.getAttrValues().split(","));
			arr.add(o);
		}
		/***
		 * 
		 * "
		 * 
		 {
			"value1": "白色",
			"value2": "10G",
			"detail": {
				"颜色": "白色",
				"重量": "10G"
			},
			"pic": "http:\/\/cdn.bianwaixingqiu.com\/3c799202012151911059070.jpg",
			"price": 100,
			"cost": 90,
			"min_price": 0,
			"ot_price": 100,
			"stock": 1000,
			"bar_code": "v1001",
			"weight": "2.00",
			"volume": "10.00",
			"brokerage": "0.00",
			"brokerage_two": "0.00"
		}, {
			"value1": "白色",
			"value2": "20G",
			"detail": {
				"颜色": "白色",
				"重量": "20G"
			},
			"pic": "http:\/\/cdn.bianwaixingqiu.com\/3c799202012151911059070.jpg",
			"price": 100,
			"cost": 90,
			"min_price": 0,
			"ot_price": 100,
			"stock": 1000,
			"bar_code": "v1002",
			"weight": "2.00",
			"volume": "10.00",
			"brokerage": "0.00",
			"brokerage_two": "0.00"
		}
		 */
		JSONArray arrValue = new JSONArray(); 
		for(StoreProductAttrValue o : attrValueList) {
			JSONObject m = new JSONObject();
			Map<String, Object> map = new HashMap<String, Object>();
			if(attrList.size() == 1) {
				m.put("value", "规格");
				map.put("123", "默认");
			} else {
				for(int i=1; i <= attrList.size(); i++) {
					StoreProductAttr attr = attrList.get(i-1);
					m.put("value" + i, o.getSuk().split(",")[o.getSuk().split(",").length-i]);
					map.put(attr.getAttrName(), o.getSuk().split(",")[o.getSuk().split(",").length-i]);
				}
			}
			m.put("detail", map);
			m.put("pic", o.getImage());
			m.put("price", o.getPrice());
			m.put("cost", o.getCost());
			m.put("ot_price", o.getOtPrice());
			m.put("stock", o.getStock());
			m.put("bar_code", o.getBarCode());
			m.put("weight", o.getWeight());
			m.put("volume", o.getVolume() + "");
			m.put("min_price", 0);
			m.put("brokerage", o.getBrokerage());
			m.put("brokerage_two", o.getBrokerageTwo() + "");
			
			arrValue.add(m);
		}
		
		String result = "{\"attr\":" + arr.toJSONString() + ",\"value\":" + arrValue.toJSONString() + "}";
		logger.info("msg1=拼接result={}",result );
		return StringUtils.getUnicode(result);
	}

	/**
	 * 设置更新 商品分类辅助表
	 * @param vo
	 */
	private void addProductCate(StoreProduct product) {
		if(!StringUtils.isNullOrBlank(product.getCateId())){
			String [] carteArray = product.getCateId().split(",");
			//一定先删除再插入 注意顺序
			storeproductCateService.deleteByProductId(product.getId());
			for(int i=0;i<carteArray.length;i++){
				//设置商品辅助分类表
			    StoreProductCate productCate = new StoreProductCate();
			    productCate.setProductId(product.getId());
			    Integer addTime=(int) (new Date().getTime()/1000);
			    productCate.setAddTime(addTime);
			    productCate.setCateId(Integer.valueOf(carteArray[i]));
			    storeproductCateService.save(productCate);
			}
		}
	}
	
	/***
	 * 更新商品属性
	 * @param storeProductAttrList
	 */
	private void addProductAttr(List<StoreProductAttr> storeProductAttrList, Integer productId) {
		if(storeProductAttrList!=null && !storeProductAttrList.isEmpty()){
			//先删除再插入
		    storeProductAttrService.deleteByProductIdAndType(productId, ProductConstants.ACTIVE_TYPE_0);
			for(int i=0;i<storeProductAttrList.size();i++){
				StoreProductAttr storeProductAttr=storeProductAttrList.get(i);
				storeProductAttr.setProductId(productId);
				storeProductAttr.setType(ProductConstants.ACTIVE_TYPE_0);
				storeProductAttrService.save(storeProductAttr);
			}
		}
	}
	
	/**
	 * 设置商品详情表
	 * @param storeProductDetailsList
	 */
	private void addStoreProductDetails(List<StoreProductDetails> storeProductDetailsList, Integer productId, String productCode) {
		if(storeProductDetailsList!=null && !storeProductDetailsList.isEmpty()){
			Map<String,Object> delProductDetailMap=new HashMap<String,Object>();
			delProductDetailMap.put("productId", productId);
			productDetailsService.deleteByProductId(productId);
			for(StoreProductDetails o : storeProductDetailsList){
				o.setProductId(productId);
				o.setProductCode(productCode);
				productDetailsService.save(o);
			}
		}
	}
	
	
	/**
	 * 设置 商品属性值表
	 * @param storeProductAttrValueList
	 * @param productId
	 */
	private void addProductAttrValue(List<StoreProductAttrValue> storeProductAttrValueList, Integer productId, Integer storeId,String productType) {
		if(!storeProductAttrValueList.isEmpty()) {
			storeProductAttrValueService.deleteByProductIdAndType(productId, ProductConstants.ACTIVE_TYPE_0);
			for(StoreProductAttrValue o : storeProductAttrValueList) {
				o.setProductId(productId);
				o.setStoreId(storeId);
				o.setUnique(StringUtils.getRandomCode(8));
				o.setOtPrice(o.getMinPrice()==null ? new BigDecimal(0) : o.getMinPrice());
				o.setCost(o.getCost()==null ? new BigDecimal(0) : o.getCost());
				o.setMinPrice(o.getMinPrice()==null ? new BigDecimal(0) : o.getMinPrice());
				o.setWeight(new BigDecimal(0));
				o.setVolume(new BigDecimal(0));
				o.setBrokerage(new BigDecimal(0));
				o.setBrokerageTwo(new BigDecimal(0));
				o.setSales(0);
				o.setType(ProductConstants.ACTIVE_TYPE_0);
				o.setStock(o.getStock());
				//suk 做升序排序
				o.setSuk(StringUtils.sortArray(o.getSuk()));
				//如果是服务类商品 库存和条码后台默认值
				if(productType.equals(ProductConstants.PRODUCT_TYPE_2)){
					o.setStock(99);
					String barCode=o.getBarCode();
					if(StringUtils.isNullOrBlank(barCode)){
						o.setBarCode("000000"+DateUtil.getDateFormateDate()+StringUtils.randomString(6,true));
					}
				}
				storeProductAttrValueService.save(o);
			}
		}
	}

	@Override
	public StoreProduct queryViewById(Integer id) {
		StoreProduct o = storeProductMappermapper.queryByPrimaryId(id);
//		Integer storeId=o.getStoreId();
//		if(StringUtils.isNoneBlank(o.getCateId())) {
//			String cateName = ""; 
//			for(String s : o.getCateId().split(",")) {
//				cateName = cateName + storeCategoryService.getFullCategoryName(Integer.parseInt(s)) + " ";
//			}
//			o.setCateName(cateName);
//		}
		return o;
	}
	public List<StoreProduct> getListProductCodeIsNull() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("productCodeNotNull", "Y");
		return storeProductMappermapper.getList(map);
	}

	@Override
	public void deleteByProductId(Integer id) {
		storeProductMappermapper.deleteByProductId(id);
	}

//	* 1.设置商品主体信息(eb_store_product)
//	 * 2.设置更新 商品分类辅助表(eb_store_product_cate)
//	 * 3.设置 商品属性表(eb_store_product_attr)
//	 * 4.设置 商品属性值表(eb_store_product_attr_value)
//	 * 5.设置商品详情表(eb_store_product_details)
//	 * 6.商品属性详情表(eb_store_product_attr_result)
	@Override
	public void delStoreProductAndDetailTable(Integer productId, Integer storeId) {
		//删除主表信息
		this.deleteByProductId(productId);
		storeProductAttrService.deleteByProductIdAndType(productId, ProductConstants.ACTIVE_TYPE_0);
		productDetailsService.deleteByProductId(productId);
		storeproductCateService.deleteByProductId(productId);
		storeProductAttrResultService.deleteByProductIdAndType(productId, ProductConstants.ACTIVE_TYPE_0);
		storeProductAttrValueService.deleteByProductIdAndType(productId, ProductConstants.ACTIVE_TYPE_0);
	}

	@Override
	public Integer countTotal(Map<String, Object> map) {
		Integer count=storeProductMappermapper.countTotal(map);
		return count;
	}

	@Override
	public PageInfo<StoreProductDto> getProcuctAndBrandListByPage(Map<String, Object> map, Integer pageNum,Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<StoreProductDto> listStoreProductSupplierDto=storeProductMappermapper.getProcuctAndBrandList(map);
		return PageUtil.toPageInfo(listStoreProductSupplierDto);
	}

	@Override
	public List<String> getProductCodeList(Integer storeId) {
		List<String> list=storeProductMappermapper.getProductCodeList(storeId);
		return list;
	}

	@Override
	public PageInfo<StoreProductSkuDto> getStoreProductSkuListByPage(Map<String, Object> map, Integer pageNum,Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<StoreProductSkuDto> listStoreProductSku=storeProductMappermapper.getStoreProductSkuList(map);
		return PageUtil.toPageInfo(listStoreProductSku);
	}

	@Override
	public List<StoreProductSkuDto> getStoreProductSkuByBarCode(Map<String, Object> map) {
		List<StoreProductSkuDto> listStoreProductSku=storeProductMappermapper.getStoreProductSkuList(map);
		return listStoreProductSku;
	}
	
}